package com.hh.game.common.base.config;

import com.alibaba.fastjson.JSON;
import com.hh.game.common.base.exception.ApplicationStartException;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;

import java.util.Map;

@Slf4j
public class RedisConfig {
    private Map<String ,Object> redisson;
    private RedissonClient redissonClient;
    private String pref;

    public void setRedisson(Map<String, Object> redis) {
        this.redisson = redis;
    }

    public RedissonClient redissonClient(){
        try {
            Config config = Config.fromJSON(JSON.toJSONString(this.redisson));
            redissonClient = Redisson.create(config);
        }catch (Exception e){
            throw new ApplicationStartException("configuration redis error: " + e.getMessage() ,e);
        }
        return redissonClient;
    }

    public void setPref(String pref) {
        this.pref = pref;
    }

    public String getPref() {
        return pref;
    }

    public void close(){
        if(redissonClient != null && !redissonClient.isShutdown()){
            redissonClient.shutdown();
        }
    }

//    @Override
//    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
//        AbstractEnvironment environment = (AbstractEnvironment)conditionContext.getEnvironment();
//       return environment.getPropertySources().stream().
//               anyMatch(source -> {
//                   if(source instanceof OriginTrackedMapPropertySource){
//                       OriginTrackedMapPropertySource origin = (OriginTrackedMapPropertySource)source;
//                       return Arrays.stream(origin.getPropertyNames()).anyMatch(name -> name.startsWith("app.redis"));
//                   }
//                   return false;
//               });
//    }
}
